import requests
from test_tools.script.path_tool import *


def print_response(response):
    log("====================================================================")
    # 状态码
    log(f"status_code => {response.status_code}")
    # 状态信息
    log(f"reason => {response.reason}")
    # 编码格式
    log(f"encoding => {response.encoding}")
    # 返回的 cookie 信息
    log(f"cookies => {response.cookies}")
    # 响应头
    log(f"headers => {response.headers}")
    # 请求消耗的时间
    log(f"elapsed => {response.elapsed}")
    # 返回字符串的数据
    log(f"text => {response.text}")
    # 返回二进制数据
    log(f"content => {response.content}")
    # 将 json 转化为字典格式输出
    if "json" in response.headers.get("Content-Type"):
        log(f"json => {response.json()}")
    log("====================================================================")


class NacosQuests:
    def __init__(self):
        log("======================================= NacosQuests =======================================")
        self.session = requests.session()
        self.is_uPdata_accessToken = False
        self.nacos_requests_config__date = None
        self.login_time = None
        self.time_interval = None
        self.accessToken = None
        self.base_url = None
        self.login_url = None
        self.namespaces_url = None
        self.configs_url = None
        self.proxies = None
        self.login_date = None
        self.namespaces_date = None
        self.configs_date = None
        self.init_date()
        self.check_token()
        self.message = ExcelToolsMessageView()

    def init_date(self):
        log("NacosQuests -> init_date")
        try:
            nacos_requests_config__date = get_json_data(path=path_tool.nacos_requests_config_path)
            self.nacos_requests_config__date = nacos_requests_config__date
            self.login_time = nacos_requests_config__date["login_time"]
            self.time_interval = nacos_requests_config__date["time_interval"]
            self.accessToken = nacos_requests_config__date["accessToken"]
            self.base_url = nacos_requests_config__date["base_url"]
            self.login_url = self.base_url + nacos_requests_config__date["login_url"]
            self.namespaces_url = self.base_url + nacos_requests_config__date["namespaces_url"]
            self.configs_url = self.base_url + nacos_requests_config__date["configs_url"]
            self.proxies = nacos_requests_config__date["proxies"]
            self.login_date = nacos_requests_config__date["login_date"]
            self.namespaces_date = nacos_requests_config__date["namespaces_date"]
            self.configs_date = nacos_requests_config__date["configs_date"]
        except Exception as e:
            log(f"{os.path.basename(__file__)} -> init_date >>> \n{e}")
            prin_error()
            self.message.show_message(f"****{os.path.basename(__file__)} >>> init_date 异常： {e}")

    def set_uPdata(self, is_uPdata: bool):
        """设置鉴权码是否立即更新"""
        log(f"NacosQuests -> set_uPdata {is_uPdata}")
        self.is_uPdata_accessToken = is_uPdata

    def check_token(self):
        """检查鉴权码是否更新"""
        log("NacosQuests -> check_token")
        if self.is_uPdata_accessToken:
            self.get_token()
            return
        if self.accessToken is None or self.accessToken == "":
            self.get_token()
        else:
            current_time = int(time.time())
            if current_time - self.login_time > self.time_interval:
                self.get_token()

    def get_token(self):
        """获取最新鉴权码"""
        log("NacosQuests -> get_token")
        try:
            url = self.login_url
            params = self.login_date['params']
            headers = self.login_date['headers']
            response = self.session.post(url=url, params=params, headers=headers)
            print_response(response)
            json_data = response.json()
            accessToken = json_data['accessToken']
            self.nacos_requests_config__date["accessToken"] = accessToken
            self.nacos_requests_config__date["login_time"] = int(time.time())
            write_json_data(path=path_tool.nacos_requests_config_path, data=self.nacos_requests_config__date)
        except Exception as e:
            log(f"{os.path.basename(__file__)} -> get_token >>> \n{e}")
            prin_error()
            self.message.show_message(f"****{os.path.basename(__file__)} >>> get_token 异常： {e}")

    def get_namespaces(self):
        """获取服务器桶配置信息"""
        log("NacosQuests -> get_namespaces")
        try:
            url = self.namespaces_url
            params = self.namespaces_date['params']
            params["accessToken"] = self.accessToken
            # headers = self.namespaces_date['headers']
            response = self.session.get(url=url, params=params)
            print_response(response)
        except Exception as e:
            log(f"{os.path.basename(__file__)} -> get_namespaces >>> \n{e}")
            prin_error()
            self.message.show_message(f"****{os.path.basename(__file__)} >>> get_namespaces 异常： {e}")

    def send_config(self, namespace, config_path):
        """上传配置文件，仅支持zip格式"""
        log(f"NacosQuests -> send_config \nnamespace:{namespace},config_path:{config_path}")
        try:
            url = self.configs_url
            params = self.configs_date['params']
            # headers = self.configs_date['headers']
            params["accessToken"] = self.accessToken
            params["namespace"] = namespace
            params["tenant"] = namespace
            response = self.session.post(url=url, params=params, files={
                "file": open(config_path, "rb")
            })
            print_response(response)
            if response.status_code == 200:
                log("NacosQuests -> send_config >>> 上传成功")
                my_print.print(f"{config_path} 上传成功")
            else:
                log(f"NacosQuests -> send_config >>> \n*****上传失败****")
                my_print.print(f"{config_path} 上传失败:", 1)
                my_print.print(f"{response.text}", 1)
        except Exception as e:
            log(f"{os.path.basename(__file__)} -> send_config >>> \n{e}")
            prin_error()
            self.message.show_message(f"****{os.path.basename(__file__)} >>> send_config 异常： {e}")


if __name__ == '__main__':
    nacos_quests = NacosQuests()
    nacos_quests.get_token()
    nacos_quests.get_namespaces()
    nacos_quests.send_config(namespace="3b8640f0-6fb5-41e6-af55-43a3e2eebb28",
                             config_path="D:/hope_city_game/dev_2.0/data/服务器Demo传表记录/hope_city2.zip")
